<template>
    <div class="User-container content-wrapper">
        <el-row :gutter="20">
            <el-col :span="orgSpanSize" v-show="visibleFilterOrg">
                <!--公司-->
                <el-row class="margin-bottom-10">
                    <el-col>
                        <el-card class="box-card" :body-style="{ padding: '0px' }">
                            <div class="clearfix card-header">
                                <span><i class="el-icon-menu" style="color:#324057"></i> 公司</span>
                            </div>
                            <el-tree :data="treeCompany" node-key="id" ref="tree"
                                     v-loading="loadingCompany"
                                     highlight-current
                                     :check-strictly="true"
                                     :default-expand-all="true"
                                     :props="defaultProps"
                                     @node-click="handleNodeClickCompany"
                            ></el-tree>
                        </el-card>
                    </el-col>
                </el-row>

                <!--部门-->
                <el-row class="margin-bottom-10">
                    <el-col>
                        <el-card class="box-card" :body-style="{ padding: '0px' }">
                            <div class="clearfix card-header">
                                <span><i class="el-icon-menu" style="color:#324057"></i> 部门</span>
                            </div>
                            <el-tree :data="treeDepartment" node-key="id" ref="tree"
                                     v-loading="loadingDepartment"
                                     highlight-current
                                     :check-strictly="true"
                                     :default-expand-all="true"
                                     :props="defaultProps"
                                     @node-click="handleNodeClickDepartment"
                            ></el-tree>
                        </el-card>
                    </el-col>
                </el-row>
            </el-col>

            <el-col :span="userSpanSize">
                <div class="filter-wrapper">
                    <el-form ref="filterForm" :model="listQuery" :inline="true">

                        <el-form-item prop="realName" size="medium">
                            <el-input v-model="listQuery.realName" placeholder="姓名"></el-input>
                        </el-form-item>

                        <el-form-item prop="account" size="medium">
                            <el-input v-model="listQuery.account" placeholder="账号"></el-input>
                        </el-form-item>

                        <el-form-item prop="sex" size="medium">
                            <el-select v-model="listQuery.sex" placeholder="性别" clearable style="width: 100px">
                                <el-option
                                        v-for="item in sexOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="status" size="medium">
                            <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
                                <el-option
                                        v-for="item in statusOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="orderBy" size="medium">
                            <el-select v-model="listQuery.orderBy" placeholder="排序" clearable style="width: 120px">
                                <el-option
                                        v-for="item in sortOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <div class="toolbar">
                            <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                            <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                            <el-button type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
                            <el-button type="danger" size="medium" icon="el-icon-delete" @click="handleBatchDelete">删除</el-button>

                            <el-button type="primary" icon="el-icon-mars-filter" size="medium" @click="handleVisibleFilterOrg">机构筛选</el-button>
                            <el-dropdown class="margin-left-10" trigger="click" @command="handleCommand">
                                <el-button type="primary" size="medium">
                                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown" style="width: 200px;">
                                    <el-dropdown-item command="addGroup">加入群组</el-dropdown-item>
                                    <el-dropdown-item command="addOrganization">加入机构</el-dropdown-item>
                                    <el-dropdown-item command="addRole">分配角色</el-dropdown-item>
                                    <el-dropdown-item command="resetPassword">重置密码</el-dropdown-item>
                                    <el-dropdown-item command="setStatusNormal" divided>设置状态：正常</el-dropdown-item>
                                    <el-dropdown-item command="setStatusForbidden">设置状态：禁用</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </el-form>
                </div>

                <el-table
                        :data="list"
                        border fit
                        highlight-current-row
                        v-loading="listLoading"
                        tooltip-effect="dark"
                        element-loading-text="给我一点时间"
                        @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column type="index" width="55" align="center"></el-table-column>

                    <el-table-column label="姓名" width="110px" align="center">
                        <template slot-scope="scope">
                            <div v-if="scope.row.isAdmin"><el-tag type="danger">{{scope.row.realName}}</el-tag></div>
                            <div v-else>{{scope.row.realName}}</div>
                        </template>
                    </el-table-column>

                    <el-table-column label="性别" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="primary" v-if="scope.row.sex === 1">男</el-tag>
                            <el-tag type="danger" v-else-if="scope.row.sex === 2">女</el-tag>
                            <el-tag type="info" v-else>未知</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="账号" width="110px" align="center">
                        <template slot-scope="scope"> {{scope.row.account}} </template>
                    </el-table-column>

                    <el-table-column label="手机号码" width="130px" align="center">
                        <template slot-scope="scope"> {{scope.row.mobile}} </template>
                    </el-table-column>

                    <el-table-column label="邮件地址" min-width="200px" align="center" show-overflow-tooltip>
                        <template slot-scope="scope"> {{scope.row.email}} </template>
                    </el-table-column>
                    <el-table-column label="状态" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
                            <el-tag type="danger" v-else>禁用</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="登录次数" width="100" align="center">
                        <template slot-scope="scope"> {{scope.row.loginCount}} </template>
                    </el-table-column>

                    <el-table-column label="最后登录IP" width="110px" min-width="" align="center">
                        <template slot-scope="scope"> {{scope.row.lastLoginIp}} </template>
                    </el-table-column>

                    <el-table-column label="最后登录时间" width="170px" align="center">
                        <template slot-scope="scope"> {{scope.row.lastLoginTime }} </template>
                    </el-table-column>

                    <el-table-column label="创建时间" width="150px" align="center">
                        <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
                    </el-table-column>

                    <el-table-column label="操作" fixed="right" width="240px" align="center">
                        <template slot-scope="scope">
                            <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
                            <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                            <el-button size="small" type="primary" icon="edit" @click="handleDetail(scope.row)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div v-show="!listLoading" class="pagination-container">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="listQuery.page"
                            :page-sizes="[10, 20, 30, 50]"
                            :page-size="listQuery.rows"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>


        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleDialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="登录账号" prop="account">
                    <el-input v-model="form.account" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="用户姓名" prop="realName">
                    <el-input v-model="form.realName" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="用户性别" prop="sex">
                    <el-select v-model="form.sex" placeholder="性别" style="width: 180px">
                        <el-option
                                v-for="item in sexOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="form.mobile" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="邮件地址" prop="email">
                    <el-input v-model="form.email" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="账号状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="2">锁定</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="详情" :visible.sync="dialogDetailVisible" @close="handleDialogCloseDetail">
            <el-tabs v-model="tabActiveName" tab-position="left">
                <el-tab-pane name="BaseInfo">
                    <span slot="label"><i class="el-icon-date"></i> 基本信息</span>
                    <el-form label-width="120px">
                        <el-form-item label="登录账号：">
                            <span>{{ userDetail.account }}</span>
                        </el-form-item>
                        <el-form-item label="用户姓名：">
                            <span>{{ userDetail.realName }}</span>
                        </el-form-item>
                        <el-form-item label="手机号码：">
                            <span>{{ userDetail.mobile }}</span>
                        </el-form-item>
                        <el-form-item label="邮件地址：">
                            <span>{{ userDetail.email }}</span>
                        </el-form-item>

                        <el-form-item label="公司：">
                            <template v-for="(item, index) in userDetail.company">
                                <el-tag type="primary" size="small" class="margin-right-5">{{ item.name }}</el-tag>
                            </template>
                        </el-form-item>
                        <el-form-item label="部门：">
                            <template v-for="(item, index) in userDetail.department">
                                <el-tag type="primary" size="small" class="margin-right-5">{{ item.name }}</el-tag>
                            </template>
                        </el-form-item>
                        <el-form-item label="群组：">
                            <template v-for="item in userDetail.groups">
                                <el-tag type="primary" size="small" class="margin-right-5">{{ item.name }}</el-tag>
                            </template>
                        </el-form-item>
                        <el-form-item label="角色：">
                            <template v-for="item in userDetail.roles">
                                <el-tag type="primary" size="small" class="margin-right-5">{{ item.name }}</el-tag>
                            </template>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <el-tab-pane name="UserPermission">
                    <span slot="label"><i class="el-icon-date"></i> 用户权限</span>
                    <user-permission :userId="getPermissionByUserId"></user-permission>
                </el-tab-pane>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogDetailVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

        <el-dialog title="加入到组" :visible.sync="dialogGroupVisible" @close="handleDialogCloseGroup">
            <div class="filter-container">
                <el-form :model="listQueryGroup" :inline="true" style="display: inline-block">
                    <el-form-item prop="name" class="filter-item">
                        <el-input v-model="listQueryGroup.name" placeholder="组名称" style="width: 200px;"></el-input>
                    </el-form-item>
                    <el-button class="filter-item" type="primary" icon="search" @click="handleFilterGroup">搜索</el-button>
                </el-form>
            </div>
            <el-table :data="listGroup"
                      v-loading="listLoadingGroup"
                      border
                      fit
                      highlight-current-row
                      style="width: 100%"
                      @row-click="selectGroup">
                <el-table-column label="序号" width="65" align="center">
                    <template slot-scope="scope"> {{scope.row.id}} </template>
                </el-table-column>

                <el-table-column label="名称" width="300px" align="center">
                    <template slot-scope="scope"> {{scope.row.name}} </template>
                </el-table-column>

                <el-table-column label="编码" width="150px" align="center">
                    <template slot-scope="scope"> {{scope.row.code}} </template>
                </el-table-column>

                <el-table-column label="备注" min-width="300px" align="center">
                    <template slot-scope="scope"> {{scope.row.remarks}} </template>
                </el-table-column>
            </el-table>
            <div v-show="!listLoadingGroup" class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChangeGroup"
                        @current-change="handleCurrentChangeGroup"
                        :current-page="listQueryGroup.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="listQueryGroup.rows"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalGroup">
                </el-pagination>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogGroupVisible = false">取 消</el-button>
                <el-button type="primary" @click="handelSaveAssignGroup">确 定</el-button>
            </div>
        </el-dialog>


        <el-dialog title="分配角色" :visible.sync="dialogRoleVisible" @close="handleDialogCloseRole">
            <div class="filter-container">
                <el-form :model="listQueryRole" :inline="true" style="display: inline-block">
                    <el-form-item prop="name" class="filter-item">
                        <el-input v-model="listQueryRole.name" placeholder="角色名称" style="width: 200px;"></el-input>
                    </el-form-item>
                    <el-button class="filter-item" type="primary" icon="search" @click="handleFilterRole">搜索</el-button>
                </el-form>
            </div>
            <el-table :data="listRole"
                      v-loading="listLoadingRole"
                      border
                      fit
                      highlight-current-row
                      style="width: 100%"
                      @selection-change="handleSelectionChangeRole">
                <el-table-column
                        type="selection"
                        width="55" align="center">
                </el-table-column>
                <el-table-column label="序号" width="65" align="center">
                    <template slot-scope="scope"> {{scope.row.id}} </template>
                </el-table-column>

                <el-table-column label="组名称" width="300px" align="center">
                    <template slot-scope="scope"> {{scope.row.name}} </template>
                </el-table-column>

                <el-table-column label="编码" width="150px" align="center">
                    <template slot-scope="scope"> {{scope.row.code}} </template>
                </el-table-column>

                <el-table-column label="备注" min-width="300px" align="center">
                    <template slot-scope="scope"> {{scope.row.remarks}} </template>
                </el-table-column>
            </el-table>
            <div v-show="!listLoadingRole" class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChangeRole"
                        @current-change="handleCurrentChangeRole"
                        :current-page="listQueryRole.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="listQueryRole.rows"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalRole">
                </el-pagination>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="handelSaveAssignRole">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="加入到组织机构" :visible.sync="dialogOrganizationVisible" @close="handleDialogCloseOrganization">

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-card class="box-card" :body-style="{ padding: '0px' }">
                        <div class="clearfix card-header">
                            <span><i class="el-icon-menu" style="color:#324057"></i> 公司</span>
                        </div>
                        <el-tree :data="treeCompany" node-key="id" ref="tree"
                                 v-loading="loadingCompany"
                                 highlight-current
                                 :check-strictly="true"
                                 :default-expand-all="true"
                                 :props="defaultProps"
                                 @node-click="handleCompanyNodeClickDialog"
                        ></el-tree>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card class="box-card" :body-style="{ padding: '0px' }">
                        <div class="clearfix card-header">
                            <span><i class="el-icon-menu" style="color:#324057"></i> 部门</span>
                        </div>
                        <el-tree :data="treeDepartment" node-key="id" ref="tree"
                                 v-loading="loadingDepartment"
                                 highlight-current
                                 :check-strictly="true"
                                 :default-expand-all="true"
                                 :props="defaultProps"
                                 @node-click="handleDeptNodeClickDialog"
                        ></el-tree>
                    </el-card>
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogOrganizationVisible = false">取 消</el-button>
                <el-button type="primary" @click="handelSaveAssignOrganization">确 定</el-button>
            </div>
        </el-dialog>

        <back-to-top></back-to-top>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex'
    import {
        created,
        updated,
        deleted,
        deletedBatch,
        selectOne,
        selectList,
        getUserDetail,
        batchResetPassword,
        batchUpdateStatus,
        addUserToGroupAssign,
        addUserToOrganizationAssign,
        addUserToRoleAssign,
    } from '@/api/upms/user'
    import { selectTree as selectTreeCompany } from '@/api/upms/company'
    import { selectTree as selectTreeDepartment } from '@/api/upms/department'
    import { selectList as selectListGroup } from '@/api/upms/group'
    import { selectList as selectListRole } from '@/api/upms/role'
    import UserPermission from "../components/UserPermission";
    import BackToTop from "../../components/BackToTop/index";


    const sexOptions = [{label: '男', key: 1}, {label: '女', key: 2}, {label: '未知', key: 3}]
    const sortOptions = [{label: '按ID升序', key: 'id asc'}, {label: '按ID降序', key: 'id desc'}]
    const statusOptions = [{label: '正常', key: 1}, {label: '锁定', key: 2}]

    export default {
        components: {
            BackToTop,
            UserPermission
        },
        name: 'User',
        computed: {
            ...mapGetters(['user'])
        },
        data() {
            return {

                list: [],
                total: null,
                listLoading: false,
                multipleSelection: [],
                visibleFilterOrg: false,
                orgSpanSize: 6,
                userSpanSize: 24,
                listQuery: {
                    page: 1,
                    rows: 10,
                    account: undefined,
                    realName: undefined,
                    status: undefined,
                    sex: undefined,
                    companyId: undefined,
                    departmentId: undefined,
                    orderBy: 'id asc'
                },
                dialogFormVisible: false,
                dialogDetailVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                sexOptions,
                statusOptions,
                sortOptions,
                form: {
                    account: '',
                    realName: '',
                    sex: 1,
                    mobile: '',
                    email: '',
                    status: 1,
                    isAdmin: 3
                },
                userDetail: {
                },
                getPermissionByUserId: null,
                tabActiveName: 'BaseInfo',
                rules: {
                    account: [
                        { required: true, message: '请输入登录账号', trigger: 'blur' },
                        { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
                    ],
                    realName: [
                        { required: true, message: '请输入真实姓名', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码'},
                        { message: '手机必须为11位数字', pattern: /^1(3|4|5|7|8)\d{9}$/ }
                    ],
                    email: [
                        { required: true, message: '邮件地址不能为空', trigger: 'blur' },
                        { type: 'email', message: '邮件格式不正确', trigger: 'blur' }
                    ]
                },

                defaultProps: {
                    label: 'name',
                    children: 'children'
                },
                /************************公司************************/
                treeCompany: [],
                loadingCompany: false,
                /************************公司************************/
                treeDepartment: [],
                loadingDepartment: false,

                dialogOrganizationVisible: false,
                selectCompanyId: undefined,
                selectDeptId: undefined,

                dataCompany: [],
                loadingCompany: false,
                dataDept: [],
                loadingDept: false,
                formCompany: {
                    id: ''
                },
                formDept: {
                    id: ''
                },


                listGroup: null,
                totalGroup: null,
                listLoadingGroup: true,
                dialogGroupVisible: false,
                selectGroupId: undefined,
                listQueryGroup: {
                    page: 1,
                    rows: 10,
                    name: undefined,
                    orderBy: 'ctime desc'
                },

                listRole: null,
                totalRole: null,
                listLoadingRole: true,
                dialogRoleVisible: false,
                multipleSelectionRole: [],
                listQueryRole: {
                    page: 1,
                    rows: 10,
                    name: undefined,
                    orderBy: 'ctime desc'
                },
            }
        },
        created() {
            this.getTableData()
        },
        methods: {
            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getTableData()
            },
            handleVisibleFilterOrg() {//显示机构过滤
                this.visibleFilterOrg = !this.visibleFilterOrg
                if(this.visibleFilterOrg) {
                    this.userSpanSize = 18
                    this.getTreeDataCompany()
                } else {
                    this.userSpanSize = 24
                }
            },
            handleResetFilter() {//重置过滤条件
                this.$refs.filterForm.resetFields()
                this.listQuery.companyId = undefined,
                this.listQuery.departmentId = undefined,
                this.getTableData()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.resetForm()
            },
            handleDialogCloseDetail() {
                this.userDetail = {}
                this.tabActiveName = 'BaseInfo'
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getTableData()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getTableData()
            },
            handleCreate() {//添加数据窗口
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {//修改数据窗口
                if(row.isAdmin) {//判断该修改的记录是否超级管理员信息
                    if(!this.user.isAdmin) {//非超级管理员，不能修改超级管理员信息
                        this.$message({ type: 'error', message: '非超级管理员，不能修改超级管理员信息' })
                        return
                    }
                }
                selectOne(row.id).then(response => {
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {//删除数据
                if(row.isAdmin) {
                    this.$message({ type: 'error', message: '该账号为管理员，不能删除' })
                    return
                }
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getTableData()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            handleBatchDelete() {//批量删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(this.multipleSelection.length > 0) {
                        let ids = []
                        for(let item of this.multipleSelection) {
                            if(!item.isAdmin) {
                                ids.push(item.id)
                            }
                        }
                        if(ids.length > 0) {
                            deletedBatch({ids: ids.join(',')}).then(response => {
                                if(response.data.status) {
                                    this.$notify({
                                        title: '成功', message: response.data.message,
                                        type: 'success', duration: 2000
                                    })
                                    this.getTableData()
                                } else {
                                    this.$notify({
                                        title: '发生错误', message: response.data.message,
                                        type: 'error', duration: 2000
                                    })
                                }
                            })
                        } else {
                            this.$notify({
                                title: '提示', message: '请选择需要删除的记录，不能包含超级管理员',
                                type: 'warning', duration: 2000
                            })
                        }
                    } else {
                        this.$notify({
                            title: '提示', message: '请选择需要删除的记录',
                            type: 'warning', duration: 2000
                        })
                    }
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {//添加数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.handleResetFilter()
                                this.dialogFormVisible = false
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        if(this.form.isAdmin) {//不能修改管理员状态
                            this.form.status = 1
                        }
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                                this.dialogFormVisible = false
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            handleDetail(row) {
                this.dialogDetailVisible = true
                this.getPermissionByUserId = row.id
                getUserDetail(row.id).then(response => {
                    this.userDetail = response.data
                })
            },
            getTableData() {
                this.listLoading = true
                selectList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            resetForm() {//重置表单
                this.$refs['form'].resetFields()
                this.form = {
                    account: '',
                    realName: '',
                    sex: 1,
                    mobile: '',
                    email: '',
                    status: 1,
                    isAdmin: 3
                }
            },
            handleCommand(command) {
                if(command === 'addGroup') {
                    this.handleAddGroup()
                } else if(command === 'addOrganization') {
                    this.handleAddOrganization()
                } else if(command === 'addRole') {
                    this.handleAddRole()
                } else if(command === 'resetPassword') {
                    this.handleResetPassword()
                } else if(command === 'setStatusNormal') {
                    this.handelUpdateStatus(1)
                } else if(command === 'setStatusForbidden') {
                    this.handelUpdateStatus(2)
                }
            },
            handleResetPassword() {//批量重置用户密码
                const ids = []
                for(var item of this.multipleSelection) {
                    ids.push(item.id)
                }
                if(ids != null && ids.length > 0) {
                    this.$confirm('确定要重置密码？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        batchResetPassword(ids).then((response) => {
                            if (response.data.status) {
                                this.$notify({
                                    title: '提示', message: '密码重置成功',
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '提示', message: response.data.message,
                                    type: 'warning', duration: 2000
                                })
                            }
                        })
                    }).catch(() => {
                        this.$message({ type: 'info', message: '已取消删除' })
                    })
                } else {
                    this.$message({
                        message: '请选择需要重置密码的记录',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handelUpdateStatus(status) {//批量修改用户状态
                const ids = []
                for(var item of this.multipleSelection) {
                    ids.push(item.id)
                }
                if(ids != null && ids.length > 0) {
                    this.$confirm('确定要修改以下用户状态？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        batchUpdateStatus({"ids": ids, "status": status}).then((response) => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '提示', message: '密码重置成功',
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '提示', message: response.data.message,
                                    type: 'warning', duration: 2000
                                })
                            }
                        })
                    }).catch(() => {
                        this.$message({ type: 'info', message: '已取消修改' })
                    })
                } else {
                    this.$message({
                        message: '请选择需要修改的记录',
                        type: 'warning', duration: 2000
                    })
                }
            },
            /***********组***********/
            handleAddGroup() {
                if(this.multipleSelection.length > 0) {
                    this.getGroupList()
                } else {
                    this.$message({
                        message: '请选择需要加入组的用户',
                        type: 'warning', duration: 2000
                    })
                }
            },
            getGroupList() {
                this.dialogGroupVisible = true
                this.listLoadingGroup = true
                selectListGroup(this.listQueryGroup).then(response => {
                    this.listGroup = response.data.list
                    this.totalGroup = response.data.total
                    this.listLoadingGroup = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoadingGroup = false
                })
            },
            handleFilterGroup() {
                this.listQueryGroup.page = 1
                this.getGroupList()
            },
            selectGroup(row, event, column) {
                this.selectGroupId = row.id
            },
            handelSaveAssignGroup() {
                if(this.selectGroupId) {
                    const ids = []
                    for(var item of this.multipleSelection) {
                        ids.push(item.id)
                    }
                    const assignData = {groupId: this.selectGroupId, userIds: ids}
                    addUserToGroupAssign(assignData).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '提示', message: '加入成功',
                                type: 'success', duration: 2000
                            })
                            this.dialogGroupVisible = false
                        } else {
                            this.$notify({
                                title: '提示', message: response.data.message,
                                type: 'warning', duration: 2000
                            })
                        }
                    })
                } else {
                    this.$message({
                        message: '请选择组',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handleSizeChangeGroup(val) {
                this.listQueryGroup.rows = val
                this.getGroupList()
            },
            handleCurrentChangeGroup(val) {
                this.listQueryGroup.page = val
                this.getGroupList()
            },
            handleDialogCloseGroup() {
                this.selectGroupId = undefined
            },

            /***********角色***********/
            handleAddRole() {
                if(this.multipleSelection.length > 0) {
                    this.getRoleList()
                } else {
                    this.$message({
                        message: '请选择需要分配角色的用户',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handleSelectionChangeRole(val) {//角色多选
                this.multipleSelectionRole = val;
            },
            handelSaveAssignRole() {
                const ids = []
                const roleIds = []
                if(this.multipleSelectionRole.length > 0) {
                    for(var item of this.multipleSelection) {
                        ids.push(item.id)
                    }
                    for(var item of this.multipleSelectionRole) {
                        roleIds.push(item.id)
                    }
                    const assignData = {roleIds: roleIds, userIds: ids}
                    addUserToRoleAssign(assignData).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '提示', message: '加入成功',
                                type: 'success', duration: 2000
                            })
                            this.dialogRoleVisible = false
                        } else {
                            this.$notify({
                                title: '提示', message: response.data.message,
                                type: 'warning', duration: 2000
                            })
                        }
                    })
                } else {
                    this.$confirm('是否要清空以下用户所有角色？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        if(this.multipleSelection.length > 0) {
                            for (var item of this.multipleSelection) {
                                ids.push(item.id)
                            }
                            const assignData = {roleIds: roleIds, userIds: ids}
                            addUserToRoleAssign(assignData).then(response => {
                                if (response.data.status) {
                                    this.$notify({
                                        title: '提示', message: '加入成功',
                                        type: 'success', duration: 2000
                                    })
                                    this.dialogRoleVisible = false
                                } else {
                                    this.$notify({
                                        title: '提示', message: response.data.message,
                                        type: 'warning', duration: 2000
                                    })
                                }
                            })
                        }
                    }).catch(() => {
                        this.$message({ type: 'info', message: '已取消清空' })
                    })
                }
            },
            getRoleList() {
                this.dialogRoleVisible = true
                this.listLoadingRole = true
                selectListRole(this.listQueryRole).then(response => {
                    this.listRole = response.data.list
                    this.totalRole = response.data.total
                    this.listLoadingRole = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoadingRole = false
                })
            },
            handleSizeChangeRole(val) {
                this.listQueryRole.rows = val
                this.getRoleList()
            },
            handleCurrentChangeRole(val) {
                this.listQueryRole.page = val
                this.getRoleList()
            },
            handleFilterRole() {
                this.listQueryRole.page = 1
                this.getRoleList()
            },
            handleDialogCloseRole() {
                this.selectRoleId = undefined
            },
            handleAddOrganization() {
                if(this.multipleSelection.length > 0) {
                    this.selectCompanyId = undefined
                    this.selectDeptId = undefined
                    this.dialogOrganizationVisible = true
                    this.getTreeDataCompany()
                } else {
                    this.$message({
                        message: '请选择需要加入组织机构的用户',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handelSaveAssignOrganization() {
                if(this.selectCompanyId && this.selectDeptId) {
                    const ids = []
                    for(var item of this.multipleSelection) {
                        ids.push(item.id)
                    }
                    const assignData = {companyId: this.selectCompanyId, departmentId: this.selectDeptId, userIds: ids}
                    addUserToOrganizationAssign(assignData).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '提示', message: '加入组织机构成功',
                                type: 'success', duration: 2000
                            })
                            this.dialogOrganizationVisible = false
                        } else {
                            this.$notify({
                                title: '提示', message: response.data.message,
                                type: 'warning', duration: 2000
                            })
                        }
                    })
                } else {
                    this.$message({
                        message: '请选择公司和部门',
                        type: 'warning', duration: 2000
                    })
                }
            },
            handleCompanyNodeClickDialog(data, node) {
                this.selectCompanyId = data.id
                this.getTreeDataDepartment(data.id)
            },
            handleDeptNodeClickDialog(data, node) {
                this.selectDeptId = data.id
                this.formDept.id = data.id
            },
            handleDialogCloseOrganization() {
                this.selectDeptId = undefined
                this.formDept.id = undefined
            },

            /************************公司************************/
            handleNodeClickCompany(data, node) {
                this.getTreeDataDepartment(data.id)

                this.listQuery.companyId = data.id
                this.listQuery.departmentId = null
                this.getTableData()
            },
            getTreeDataCompany() {//获取数据列表
                this.loadingCompany = true
                selectTreeCompany().then(response => {
                    this.treeCompany = response.data
                    this.loadingCompany = false
                }).catch(error => {
                    console.log(error)
                    this.loadingCompany = false
                })
            },

            /************************部门************************/
            handleNodeClickDepartment(data, node) {
                this.listQuery.departmentId = data.id
                this.getTableData()
            },
            getTreeDataDepartment(companyId) {//获取数据列表
                this.loadingDepartment = true
                selectTreeDepartment({companyId: companyId}).then(response => {
                    this.treeDepartment = response.data
                    this.loadingDepartment = false
                }).catch(error => {
                    console.log(error)
                    this.loadingDepartment = false
                })
            },
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .card-header{
        border-bottom: 1px solid #d1dbe5; padding: 15px 20px 15px 7px;
    }
    .el-card__body{
        .el-tree{
            border: 0px;
        }
    }

    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 30%;
    }
</style>